package com.java.Servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

// http://localhost:8090/java-web/http-servlet-response?type=text
@WebServlet("/http-servlet-response")
public class HttpServletResponseAPI extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("type");

        if ("text".equals(type)) {
            // 响应文字给客户端
            resp.setContentType("text/html;charset=utf-8");

            PrintWriter printWriter = resp.getWriter();
            printWriter.println("你好！");
            printWriter.close();
        } else if ("file".equals(type)) {
            // 响应文件给客户端
            String path = "JavaWeb\\src\\com\\java\\Servlet\\files\\syx.jpg";
            String filename = path.substring(path.lastIndexOf("\\") + 1);
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

            FileInputStream fileInputStream = new FileInputStream(path);
            ServletOutputStream outputStream = resp.getOutputStream();

            int length = 0;
            byte[] buffers = new byte[1024];
            while ((length = fileInputStream.read(buffers)) > 0) {
                outputStream.write(buffers, 0, length);
            }

            outputStream.close();
            fileInputStream.close();
        } else if ("captcha".equals(type)) {
            // 响应图片给客户端
            resp.setContentType("image/jpeg");
            resp.setDateHeader("expires", -1);
            resp.setHeader("Cache-Control", "no-catch");
            resp.setHeader("Pragma", "no-catch");
            resp.setHeader("refresh", "3"); // 3s刷新一次

            BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB); // 内存中创建图片
            Graphics2D graphics2D = (Graphics2D) image.getGraphics(); // 获取2D画笔
            graphics2D.setColor(Color.WHITE); // 设置笔颜色
            graphics2D.fillRect(0, 0, 80, 20); // 设置填充范围
            graphics2D.setColor(Color.BLUE); // 设置笔颜色
            graphics2D.setFont(new Font(null, Font.BOLD, 20)); // 设置文字样式
            graphics2D.drawString(new Long(Math.round(Math.random() * 1000)).toString(), 0, 20);

            ImageIO.write(image, "jpg", resp.getOutputStream());
        }

        // sendRedirect：重定向
        // resp.sendRedirect("/dispatcher");
    }
}
